<?php
$loader->requireOnce('ordo/QueueRoom.class.php');

$loader->requireOnce('includes/EnumerationConstant.class.php');

class C_Department extends Controller {
	/* The maximum number of patients per bed. */
    const MAX_PATIENTS_PER_ONE_BED = 5; 
	
    var $logger;
	var $template_mod;					
	
	function C_Department($template_mod = "general") {
		parent::Controller();
		$this->logger = &LoggerManager::getLogger('core.controllers.C_Department');
		if (Celini::getCurrentController() == 'Department') {
			$menu =& Menu::getInstance();
			$menu->currentSection = 'admin';
		}
		$this->template_mod = $template_mod;		
		$this->view->path = 'department';
		$this->setLayout('admin');
	}	
	
	public function actionFilterServiceAjax() {
		$deptId = $_GET['department_id']; 
		//TODO @Localization
		$serv = Celini::newORDO('Service');
		$result = $serv->fromDepartment($deptId);
		$responseText = "";
		foreach ($result as $serviceId=>$name) {			
			$responseText .= "<option value=\"$serviceId\" label=\"$name\">$name</option>";
		}		
		return $responseText;
	}
	
	public function actionViewDepartment(){		
		return $this->view->render('display.html');
	}
	
	public function actionAddDepartment(){
		$department = Celini::newORDO('Department');
		$departmentId = $department->addDepartment($_GET);
		$newDep = $department->getDepartment($departmentId);
		// Build response		
		return $this->buildDepartmentTableResponse($newDep);;
	}
	
	public function actionAddRoom(){
		$input = $_GET;
		if ($input['room_department'] == 'empty') $input['room_department'] = '';
		if ($input['room_type'] == 'empty') {
			$input['room_type'] = 0;
		}
				
		$room = Celini::newORDO('Room');
		$roomId = $room->addRoom($input);
		$newRoom = $room->getRoom($roomId);		
		if ($_GET['encounter_room'] == 'true') {			
			Celini::newORDO('QueueRoom')->add($roomId, QueueRoom::ENCOUNTER);
		}
		// Build response		
		return $this->buildRoomTableResponse($newRoom);;
	}	
	
	public function actionGetAllDepartmentsTable(){
		//TODO @Localization
		
		$dep = Celini::newORDO('Department');
		$departments = $dep->getAllDepartments();
		$response = '';
		foreach ($departments as $department){
			$response = $response.$this->buildDepartmentTableResponse($department);
		}
		return $response;
	}
	
	public function actionGetAllRoomsTable(){		
		//TODO @Localization		
		$room = Celini::newORDO('Room');
		if ($_GET['filter_department'] == 'null') $filter = 'all';
		else $filter = $_GET['filter_department'];
		$rooms = $room->getAllRooms($filter);
		$response = '';
		foreach ($rooms as $room){
			$response = $response.$this->buildRoomTableResponse($room);
		}
		return $response;
	}	
	
	public function actionGetAllDepartmentsSelect(){
		//TODO @Localization
		$dep = Celini::newORDO('Department');
		$departments = $dep->getAllDepartments();
		$response = '';
		foreach ($departments as $department){
			$response = $response.$this->buildDepartmentSelectResponse($department, 'no');
		}
		return $response;
	}

	public function actionRemoveOrUndoDepartment(){		
		$dep = Celini::newORDO('Department');
		$dep->removeOrUndoDepartment($_GET['department_id'], $_GET['activity']);		
		return $_GET['department_id'];
	}
	
	public function actionRemoveOrUndoRoom(){
		$dep = Celini::newORDO('Room');
		$dep->removeOrUndoRoom($_GET['room_id'], $_GET['activity']);
		return $_GET['room_id'];
	}	
	
	public function actionSaveDepartment(){
		$dep = Celini::newORDO('Department');
		$dep->updateDepartment($_POST);
		$newDep = $dep->getDepartment($_POST['department_id']);
		return json_encode($newDep);
	}

	public function actionSaveRoom(){
		$input = $_POST;
		if ($input['room_department'] == 'empty' || $input['room_department'] == '') $input['room_department'] = 0;		
	    if ($input['room_type'] == 'empty') {
            $input['room_type'] = 0;
        }
		$room = Celini::newORDO('Room');
		$room->updateRoom($input);
		$newRoom = $room->getRoom($_POST['room_id']);
		return json_encode($newRoom);
	}	
	
	public function actionGetDepartmentName(){
		//TODO @Localization		
		$dep = Celini::newORDO('Department');
		$result = $dep->getDepartment($_GET['department_id']);
		return $result['name'];
	}
	
	public function actionGetAllRoomDepartments(){
		// Get department of current room
		//TODO @Localization
		
		$obj = Celini::newORDO('Room');
		$room = $obj->getRoom($_GET['room_id']);
		$dep = Celini::newORDO('Department');
		$departments = $dep->getAllDepartments();
		$response = '';
		foreach ($departments as $department){
			if ($department['department_id'] == $room['department_id'])
				$response = $response.$this->buildDepartmentSelectResponse($department, 'select');
			else $response = $response.$this->buildDepartmentSelectResponse($department, 'no');
		}
		return $response;		
	}
	
	private function buildDepartmentTableResponse($newDep){
		//TODO @Localization
		$response = "<tr id='".$newDep['department_id']."'>".
						"<td><span id='department_".$newDep['department_id']."_name_span'>".$newDep['name']."</span><input style='display:none' type='text' id='department_".$newDep['department_id']."_name_input' value=''></td>".
						"<td><span id='department_".$newDep['department_id']."_description_span'>".$newDep['description']."</span><input style='display:none' type='text' id='department_".$newDep['department_id']."_description_input' value=''></td>".
		                "<td><span id='department_".$newDep['department_id']."_status_span'";
		if ($newDep['deleted'] == 0) {
			$response	.=	">" . L10nHelper::_("In Use")
						.	"</span></td>";
						
		    $response	.=	"<td><span id='department_".$newDep['department_id']."_remove_span'>"
		    			.	"<a href='javascript:removeDepartment(".$newDep['department_id'].")' title='" . L10nHelper::_("Delete") . "'>"
		    			.   "<img src=\"../images/lock_small.png\" alt=\"" . L10nHelper::_("Delete") . "\"></img>"
		    			. 	"</a>";
		} else if ($newDep['deleted'] == 1) {
			$response	.=	"class='impression'>" . L10nHelper::_("Temporary delete")
						.	"</span></td>";
						
			$response	.=	"<td><span id='department_".$newDep['department_id']."_remove_span'>"
						.	"<a href='javascript:undoDepartment(".$newDep['department_id'].")' title='" . L10nHelper::_("Reuse") . "'>"
						.	"<img src=\"../images/unlock_small.png\" alt=\"" . L10nHelper::_("Reuse") . "\"></img>"
                      	.	"</a>";
		}
		$response .=	"</span>".
		                "<td><a id='department_".$newDep['department_id']."_edit' href='javascript:editDepartment(".$newDep['department_id'].")'>".L10nHelper::_("Edit")."</a>".
						"<a id='department_".$newDep['department_id']."_save' style='display:none' href='javascript:saveDepartment(".$newDep['department_id'].")'>".L10nHelper::_("Save")."</a></td>".
						"<td><a id='department_".$newDep['department_id']."_cancel' style='display:none' href='javascript:cancelDepartment(".$newDep['department_id'].")'>".L10nHelper::_("Cancel")."</a></td>".						
					"</tr>";	
		return $response;	
	}
	
	private function buildDepartmentSelectResponse($newDep, $selected){
		if ($selected == 'no')
			$response = "<option id='".$newDep['department_id']."' name='".$newDep['name']."' value='".$newDep['department_id']."'>".$newDep['name']."</option>";
		else $response = "<option selected id='".$newDep['department_id']."' name='".$newDep['name']."' value='".$newDep['department_id']."'>".$newDep['name']."</option>";	
		return $response;	
	}

	private function buildRoomTableResponse($newRoom){
		$roomId = $newRoom['room_id'];
		$qr = Celini::newORDO('QueueRoom');
		//@localization
		$encounterRoom = L10nHelper::_('No');
		if ($qr->isExist($roomId, QueueRoom::ENCOUNTER)) {
			$encounterRoom = L10nHelper::_('Yes');
		}
		$roomTypeText = '';		
		if (isset($newRoom['room_type'])) {
		    $roomTypeText = Utils::getEnumTextByKey(EnumerationConstant::ENUM_ROOM_TYPE, $newRoom['room_type']);		    	    
		}
		$response = "<tr id='". $roomId ."'>".
						"<td><span id='room_".$roomId."_department_span'>".$newRoom['department_name']."</span><form><select style='display:none' id='room_".$roomId."_department_select'></select></form></td>".		
						"<td><span id='room_".$roomId."_name_span'>".$newRoom['room_name']."</span><input style='display:none' type='text' id='room_".$roomId."_name_input' value=''></td>".
						"<td><span id='room_".$roomId."_description_span'>".$newRoom['description']."</span><input style='display:none' type='text' id='room_".$roomId."_description_input' value=''></td>".
						"<td><span id='room_".$roomId."_encounter_room_span'>".$encounterRoom."</span><input style='display:none' type='checkbox' id='room_".$roomId."_encounter_room_input'></td>".
		                "<td><span id='room_".$roomId."_room_type_span'>".$roomTypeText."</span><form><select style='display:none' id='room_".$roomId."_room_type_select'></select></form></td>".
		                "<td><span id='room_".$roomId."_status_span'";
	   if ($newRoom['deleted'] == 0) {
	   		$response	.=	">" . L10nHelper::_("In Use")
	   					.	"</span></td>";
	   					
            $response	.= "<td><span id='room_".$roomId."_remove_span'>"
            			.    "<a href=\"javascript:removeRoom($roomId)\" title='" . L10nHelper::_("Delete") . "'>"
                      	.         "<img src=\"../images/lock_small.png\" alt=\"" . L10nHelper::_("Delete") . "\"></img>"
                      	.     "</a>";
        } else if ($newRoom['deleted'] == 1) {
	   		$response	.=	"class='impression'>" . L10nHelper::_("Temporary delete")
	   					.	"</span></td>";
	   					
            $response 	.= "<td><span id='room_".$roomId."_remove_span'>"
            			.    "<a href=\"javascript:undoRoom($roomId)\" title='" . L10nHelper::_("Reuse") . "'>"
                      	.         "<img src=\"../images/unlock_small.png\" alt=\"" . L10nHelper::_("Reuse") . "\"></img>"  
                      	.     "</a>";           
        }
        $response .=    "</span></td>".
						"<td><a id='room_".$roomId."_edit' href='javascript:editRoom(".$roomId.")'>".L10nHelper::_("Edit")."</a>".
						"<a id='room_".$roomId."_save' style='display:none' href='javascript:saveRoom(".$roomId.")'>".L10nHelper::_("Save")."</a></td>".
						"<td><a id='room_".$roomId."_cancel' style='display:none' href='javascript:cancelRoom(".$roomId.")'>".L10nHelper::_("Cancel")."</a></td>".
						
					"</tr>";	
		return $response;	
	}
	
    /**
     * Get list of department, bed price type enumeration to create one bed.
     * 
     * @return array of data
     */
    public function actionGetDataToCreateBed() {
        // departments
        $departments = $this->actionGetAllDepartmentsSelect();
        // bed price types
        $em = Celini::enumManagerInstance();
        $priceTypes = Utils::getEnumArrayKey(EnumerationConstant::ENUM_BED_PRICE_TYPE);
        asort($priceTypes);
        $priceTypeRes = '';
        foreach ($priceTypes as $key => $val) {
            $priceTypeRes = $priceTypeRes . $this->buildPriceTypeResponse($key, $val, 'no');
        }
        $modelMap = array('departments' => $departments,
                          'maxPatients' => C_Department::MAX_PATIENTS_PER_ONE_BED,
                          'priceTypes'  => $priceTypeRes);
        return json_encode($modelMap);
    }

    private function buildPriceTypeResponse($enumValId, $value, $selected) {        
        if ($selected == 'no') {
            $response = "<option id='" . $enumValId. "' value='" . $enumValId . "'>" . $value . "</option>";
        } else {
        	$response = "<option selected id='" . $enumValId. "' value='" . $enumValId . "'>" . $value . "</option>";
        }
        return $response;
    }
    
    /**
     * Get all rooms of a specific department and return response of rooms to client.
     * @return string Response of rooms
     */
	public function actionGetRoomsSelect() {
		$deptId = $_GET['deptId'];
        $response = $this->getAllRoomsForDept($deptId, 'no');
        return $response;
		
	}
	
	private function getAllRoomsForDept($deptId, $roomId) {
		$rooms = Celini::newORDO('Room')->getAllRooms($deptId);
        $response = '';     
        foreach ($rooms as $room) {
        	if ($roomId == 'no' || $room['room_id'] != $roomId) {
                $option = "<option id='" . $room['room_id']. "' value='" . $room['room_id'] . "'>". $room['room_name'] . "</option>";
        	} elseif ($room['room_id'] == $roomId) {
        		$option = "<option selected id='" . $room['room_id']. "' value='" . $room['room_id'] . "'>". $room['room_name'] . "</option>";
        	}
            $response = $response . $option;
        }
        return $response;
	}
	
	/**
	 * Check if bed code existed or not, then create new bed in database.
	 * @return string
	 */
	public function actionAddBed() {
	    $input = $_GET;        
        $bed = Celini::newORDO('Bed');
        $exist = $bed->checkExisted($input['deptId'], $input['roomId'], $input['bedCode']);
        if ($exist) {
        	$this->logger->warn("Bed code '" . $input['bedCode'] . "' duplicated");
        	return "existed";
        } else {
            $bedId = $bed->addBed($input);
            $this->logger->info("Created bed '" . $input['bedCode'] . "'");
            
            $newBed = $bed->getBed($bedId);
            // Build response       
            return $this->buildBedTableResponse($newBed, true);
        }
	}
	
	private function buildBedTableResponse($bed, $hasTR) {
		$bedId = $bed['bed_id'];
		$response = '';
		if ($hasTR) {
			$response = $response . "<tr id='" . $bedId . "'>";
		}
		$response = $response
		          .     "<td>"
                  .         "<span id='bed_".$bedId."_department_span'>" . $bed['department_name'] . "</span>"
                  .         "<select style='display:none' id='bed_".$bedId."_department_select'" 
                  .              "onChange=\"javascript:getRoomsSelect('bed_".$bedId."_department_select', 'bed_".$bedId."_room_select');\">"
                  .         "</select>"
                  .     "</td>"
                  .     "<td>"
                  .         "<span id='bed_".$bedId."_room_span'>" . $bed['room_name'] . "</span>"
                  .         "<select style='display:none' id='bed_".$bedId."_room_select'></select>"
                  .     "</td>"
		          .     "<td>"
		          .         "<span id='bed_".$bedId."_code_span'>" . $bed['code'] . "</span>"
		          .         "<input style='display:none' type='text' id='bed_".$bedId."_code_input' value=''>"
		          .     "</td>"
		          .     "<td>"
                  .         "<span id='bed_".$bedId."_maxPatients_span'>".$bed['max_patients']."</span>"
                  .         "<select style='display:none;width:50px' id='bed_".$bedId."_maxPatients_select'></select>"
                  .     "</td>"
		          .     "<td>"
		          .         "<span id='bed_".$bedId."_price_span'>".$bed['price']."</span>"		          
		          .         "<input style='display:none;max-width:5em' type='text' id='bed_".$bedId."_price_input' value=''>"
		          .         "/"
		          .         "<span id='bed_".$bedId."_priceType_span'>". Utils::getEnumTextByKey(EnumerationConstant::ENUM_BED_PRICE_TYPE, $bed['price_type']) . "</span>"
		          .         "<select style='display:none' id='bed_".$bedId."_priceType_select'></select>"
		          .     "</td>"
		          .     "<td>"
		          .         "<span id='bed_".$bedId."_status_span'";
		if ($bed['deleted'] == 0) {
			$response .= 	">" . L10nHelper::_("In Use")
					  .		"</span>"
					  . "</td>"
					  . "<td>"
		    		  .     "<span id='bed_".$bedId."_remove_span'>"
		    		  .        "<a href=\"javascript:removeBed($bedId)\" title='" . L10nHelper::_("Delete") . "'>"
		              .             "<img src=\"../images/lock_small.png\" alt=\"" . L10nHelper::_("Delete") . "\"></img>"
		              .        "</a>";
		} else if ($bed['deleted'] == 1) {
			$response .= " class='impression'>" . L10nHelper::_("Temporary delete")
					  .     "</span>"
					  . "</td>"
					  . "<td>"
					  .     "<span id='bed_".$bedId."_remove_span'>"
					  .        "<a href=\"javascript:undoBed($bedId)\" title='" . L10nHelper::_("Reuse") . "'>"
			          .             "<img src=\"../images/unlock_small.png\" alt=\"" . L10nHelper::_("Reuse") . "\"></img>"  
			          .        "</a>";
		}
		$response .=        "</span"
		          .     "</td>"
		          .     "<td>"
		          .         "<a id='bed_".$bedId."_edit' href='javascript:editBed(".$bedId.")'>".L10nHelper::_("Edit")."</a>"
		          .         "<a id='bed_".$bedId."_save' style='display:none' href='javascript:saveBed(".$bedId.")'>".L10nHelper::_("Save")."</a>"
		          .     "</td>"
		          .     "<td>"
		          .         "<a id='bed_".$bedId."_cancel' style='display:none' href='javascript:cancelBed(".$bedId.")'>".L10nHelper::_("Cancel")."</a>"
		          .     "</td>";
	    if ($hasTR) {
            $response = $response . "</tr>";
        }
		return $response;
	}
	
	/**
	 * Get all beds of a specific department and room.
	 * @return string list of beds in html response
	 */
	public function actionGetAllBedsTable() {
		$bed = Celini::newORDO('Bed');
		$beds = $bed->getListOfBeds($_GET['deptId'], $_GET['roomId']);
		$response = "";
		foreach ($beds as $item) {
			$response = $response . $this->buildBedTableResponse($item, true);
		}
		return $response;
	}
	
    /**
     * Get list of department, bed price type enumeration ... to edit one bed.
     * 
     * @return array of data
     */
    public function actionGetDataToEditBed() {
    	$bedId = $_GET['bedId'];
    	$bed = Celini::newORDO('Bed')->getBed($bedId);
    	
        // departments
        $dep = Celini::newORDO('Department');
        $departments = $dep->getAllDepartments();
        $deptRes = '';
        foreach ($departments as $department) {
            if ($department['department_id'] == $bed['department_id']) {
            	$deptRes = $deptRes . $this->buildDepartmentSelectResponse($department, 'select');
            } else {
            	$deptRes = $deptRes . $this->buildDepartmentSelectResponse($department, 'no');
            }
        }
        // rooms
        $roomRes = $this->getAllRoomsForDept($bed['department_id'], $bed['room_id']);
        
        // maxPatients
        $maxPatientsRes = '';
        for ($i = 1; $i <= C_Department::MAX_PATIENTS_PER_ONE_BED; $i++) {
        	if ($i == $bed['max_patients']) {
        	    $maxPatientsRes = $maxPatientsRes. "<option selected value='" . $i . "'>" . $i . "</option>";
        	} else {
        		$maxPatientsRes = $maxPatientsRes. "<option value='" . $i . "'>" . $i . "</option>";
        	}
        }
        
        // bed price types
        
        $priceTypes = Utils::getEnumArrayKey(EnumerationConstant::ENUM_BED_PRICE_TYPE);
        asort($priceTypes);
        $priceTypeRes = '';
        foreach ($priceTypes as $key => $val) {
        	if ($key == $bed['price_type']) {
                $priceTypeRes = $priceTypeRes . $this->buildPriceTypeResponse($key, $val, 'select');
        	} else {
        		$priceTypeRes = $priceTypeRes . $this->buildPriceTypeResponse($key, $val, 'no');
        	}
        }
        
        $modelMap = array('departments' => $deptRes,
                          'rooms' => $roomRes,
                          'maxPatients' => $maxPatientsRes,
                          'priceTypes'  => $priceTypeRes);
        return json_encode($modelMap);
    }
	
    /**
     * After modifying one bed, check if this bed existed or not, save this bed into database.
     * @return string
     */
    public function actionSaveBed() {
    	$input = $_GET;        
        $bed = Celini::newORDO('Bed');
        $exist = $bed->checkExisted($input['deptId'], $input['roomId'], $input['bedCode']);
        if ($exist && $exist != $input['bedId']) {
        	$this->logger->warn("Bed code '" . $input['bedCode'] . "' duplicated");
            return "existed";
        } else {
            $bed->updateBed($input);
            $this->logger->info("Updated bed '" . $input['bedId'] . "'");
            
            $updatedBed = $bed->getBed($input['bedId']);
            // Build response       
            return $this->buildBedTableResponse($updatedBed, false);
        }
    }
    
    /**
     * Remove or undo one bed.
     * @return the id of removed/undo bed
     */
    public function actionRemoveOrUndoBed() {
    	$bed = Celini::newORDO('Bed');
    	$bed->removeOrUndoBed($_GET['bedId'], $_GET['activity']);
    	if ($_GET['activity'] == 'remove') {
    	    $this->logger->info("Removed bed '" . $_GET['bedId'] . "'");
    	} else {
    	    $this->logger->info("Undo bed '" . $_GET['bedId'] . "'");
    	}
    	return $_GET['bedId'];
    }
    
    private function buildRoomTypeResponse($enumValId, $value, $selected) {
        
        if ($selected == 'no') {
            $response = "<option id='" . $enumValId. "' value='" . $enumValId . "'>" . $value . "</option>";
        } else {
            $response = "<option selected id='" . $enumValId. "' value='" . $enumValId . "'>" . $value . "</option>";
        }
        return $response;
    }
    
    /**
     * Get all room types for select box on UI.
     * @return string list of room types in html response
     */
    public function actionGetRoomTypesSelect() {
        $em = Celini::enumManagerInstance();
        $roomTypes = Utils::getEnumArrayKey(EnumerationConstant::ENUM_ROOM_TYPE);
        
        $selRoomType = '';
        if (isset($_GET['room_id'])) {
        	$room = Celini::newORDO('Room')->getRoom($_GET['room_id']);
        	if (isset($room['room_type'])) {
        		$selRoomType = $room['room_type'];
        	}
        }
        $roomTypeRes = '';
        foreach ($roomTypes as $key => $val) {
        	if ($key == $selRoomType) {
                $roomTypeRes = $roomTypeRes . $this->buildRoomTypeResponse($key, $val, 'select');
        	} else {
        		$roomTypeRes = $roomTypeRes . $this->buildRoomTypeResponse($key, $val, 'no');
        	}
        }
        return $roomTypeRes;
    }
}

?>